
package com.innovamed.websocket.service;

import com.innovamed.websocket.handler.SocketServer;
import com.innovamed.websocket.model.QueueMsg;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import cn.hutool.json.JSONUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * Copyright: Copyright (c) Jun_Zhou @PackageName:com.innovamed.websocket.service @Description:
 * 该类的功能描述
 *
 * @version: v1.0.0
 * @author: JunZhou @Email: 1769676159@qq.com @Site: CERNO
 * @date: 2019/8/24 17:14
 */
@Component
public class MyConsumer extends DefaultConsumer
{
	private static final Logger	log	= LoggerFactory.getLogger(MyConsumer.class);
	private static Channel		channel;
	
	public MyConsumer()
	{
		super(MyConsumer.channel);
	}
	
	/**
	 *  @param 消费者标签
	   *    消费发送过来的消息;
	 */
	@Override
	public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException
	{
		logMsg(consumerTag, envelope, properties, body);
		String msgBody = new String(body);
		sendMsgToClient(msgBody);
		//手动应答，表示已经接收到消息，rabbitmq可以将此消息从队列中删除
		MyConsumer.channel.basicAck(envelope.getDeliveryTag(), false);
	}
	
	/**
	  * 推送消息到指定的客户端;
	 * @param msgBody
	 */
	private void sendMsgToClient(String msgBody)
	{
		QueueMsg msgBodyIns = JSONUtil.toBean(msgBody, QueueMsg.class);
		String sessionKey = msgBodyIns.getSessionId();
		String msg = msgBodyIns.getMsgBody();
		SocketServer.sendMessage(msg, sessionKey);
	}
	
	/**
	   * 日志打印传送过来的消息;
	 * @param consumerTag
	 * @param envelope
	 * @param properties
	 * @param body
	 */
	public void logMsg(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
	{
		log.info("consumerTag: " + consumerTag);
		log.info("envelope: " + envelope);
		log.info("properties: " + properties);
		log.info("body: " + new String(body));
		log.info("-----consume--message--create--by--JunZhou-----");
	}
	
	public void setChannel(Channel channel)
	{
		MyConsumer.channel = channel;
	}
}
